import React, { PureComponent } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Tabs,
  Input,
  Row,
  Col,
  Select,
  Divider,
  Modal,
  Table,
  Tooltip,
  message,
} from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import DescriptionList from '@/components/DescriptionList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import downloadFile from '@/utils/utils';
import styles from '@/utils/utils.less';
import style from './style.less';
import Customer from '../../components/Customer';
import getSys from './judgeSys';

const FormItem = Form.Item;
const { TabPane } = Tabs;
const { Description } = DescriptionList;
const { Option } = Select;
@connect(({ annualbasic, loading, login }) => ({
  annualbasic,
  loading: loading.effects['annualbasic/getBaseInfo'],
  login,
  loadingEmp: loading.effects['annualbasic/getEmp'],
  loadingCust: loading.effects['annualbasic/getCust'],
}))
@Form.create()
class DetailInfor extends PureComponent {
  state = {
    selectedRows: [],
    selectedRowKeys: [],
    visAccoNum: false,
    operationIshow: {
      title: '操作',
      render: (text, record) => <a onClick={() => this.detailUpdate(record)}>修改</a>,
    },
    current:1,
    pageSize:10
  };

  tableSearchLayout = {
    labelCol: { md: { span: 7 } },
    wrapperCol: { md: { span: 17 } },
  };

  componentDidMount() {
    const {
      dispatch,
      location,
      annualbasic: {
        pageData: { pagination },
        activeKeyDetail,
      },
      login,
    } = this.props;

    const { systemList, baseUser } = login;
    const userType = getSys(systemList, baseUser, location);
    dispatch({
      type: 'annualbasic/getBaseInfo',
      payload: {
        yearAdjTskId: location.query.yearAdjTskId,
        userType,
        tabClickState: location.query.activeKey,
      },
    });
    this.setState(
      {
        userType,
        tempActiveKey: location.query.activeKey,
        yearAdjTskId: location.query.yearAdjTskId,
      },
      () => this.getList(activeKeyDetail, pagination.current, pagination.pageSizes)
    );
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    const oper = {
      yearAdjTskId: null,
      areaId: null,
      adjYm: null,
      adjTskBeginDate: null,
      adjTskEndDate: null,
      validYm: null,
      billUpdtWay: '1',
      activeKeyDetail: '1',
      diffHandle: [],
      listAdjAcco: [],
      fileListOld: [],
      affix: '',
      adjYear: null,
      accoNum: null,
      listAccoId: null,
      areaName: null,
      custNum: null,
      empNum: null,
      remark: null,
      pageDataDetail: {
        list: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
        },
      },
    };
    dispatch({
      type: 'annualbasic/updateModelData',
      payload: oper,
    });
  }

  getList = (activeKeyDetail = '1', currentPage = 1, pageSize = 10) => {
    const { dispatch, location, form } = this.props;
    const { operationIshow, tempActiveKey, userType } = this.state;
    const pageArg = { currentPage, pageSize };
    const getFieldsList = form.getFieldsValue();
    dispatch({
      type: 'annualbasic/updateModelData',
      payload: { activeKeyDetail },
    });
    if (Number(activeKeyDetail) === 1) {
      dispatch({
        type: 'annualbasic/getCust',
        payload: {
          oper: {
            yearAdjTskId: location.query.yearAdjTskId,
            pageArg,
            custId: getFieldsList.custId,
            state: getFieldsList.state,
            tabClickState: tempActiveKey,
          },
          userType,
        },
      });
    } else {
      dispatch({
        type: 'annualbasic/getEmp',
        payload: {
          oper: {
            yearAdjTskId: location.query.yearAdjTskId,
            pageArg,
            custId: getFieldsList.custId,
            empName: getFieldsList.empName,
            certNo: getFieldsList.certNo,
            tabClickState: tempActiveKey,
          },
          userType,
        },
      }).then(res => {
        // 只有运行系统里-详情-雇员列表中有修改
        if (res) {
          if (
            (Number(userType) === 4 || userType === 'independence') &&
            Number(tempActiveKey) === 4
          ) {
            dispatch({
              type: 'annualbasic/updateDetailtable',
              payload: operationIshow,
            });
          }
        }
      });
    }
  };

  getEmpList = () => {};

  tabPaneChange = activeKeyDetail => {
    const { dispatch } = this.props;
    const oper = {
      pageDataDetail: {
        list: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
        },
      },
    };
    dispatch({
      type: 'annualbasic/updateModelData',
      payload: oper,
    });
    this.getList(activeKeyDetail);
  };

  handleStandardTableChange = pagination => {
    const {
      annualbasic: { activeKeyDetail },
    } = this.props;
    this.getList(activeKeyDetail, pagination.current, pagination.pageSize);
    this.setState({
      current: pagination.current,
      pageSize: pagination.pageSize
    })
  };

  close = () => {
    router.goBack();
  };

  onAccoNum = listAccoId => {
    const { dispatch } = this.props;
    this.setState({
      visAccoNum: true,
    });
    dispatch({
      type: 'annualbasic/fetchAccoName',
      payload: listAccoId,
    });
  };

  okAccoNum = () => {
    this.setState({
      visAccoNum: false,
    });
  };

  cancelAccoNum = () => {
    this.setState({
      visAccoNum: false,
    });
  };

  addLink = matinfo =>
    matinfo.split(',').map(item => (
      <span key={item.split('|')[0]}>
        <a onClick={() => this.downLoad(item)}>{item.split('|')[1]}</a>
      </span>
    ));

  downLoad = item => {
    const file = item.split('|');
    downloadFile({ fileId: file[0], fileName: file[1] });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  };

  downCsAddEmp = () => {
    const { yearAdjTskId } = this.state;
    const oper = {
      yearAdjTskId,
    };
    downloadFile(oper, '/osApi/annualAdj/custCollectAddEmpByOs/downFile', 'POST');
  };

  downloadExcel = record => {
    const {
      annualbasic: { areaId },
    } = this.props;
    const { userType } = this.state;
    const oper = {
      yearAdjTskId: record.yearAdjTskId,
      custId: record.custId,
      areaId,
    };
    let url = '';
    // 运行和客服;
    if (Number(userType) === 4 || Number(userType) === 1) {
      url = '/osApi/annualAdj/custCollectByCs/downFile';
    }
    // 自主
    if (String(userType) === 'independence') {
      url = '/osApi/annualAdj/independentSupp/collect/downFile';
    }
    // 接单
    if (String(userType) === 'receive') {
      url = '/osApi/annualAdj/independentSupp/collect/downFile';
    }
    // 发单
    if (String(userType) === 'send') {
      url = '/osApi/annualAdj/custCollectBySend/downFile';
    }
    downloadFile(oper, url, 'POST');
  };

  detailUpdate = record => {
    this.setState({
      visUpdate: true,
      updateInfor: record,
      tskDetId: record.tskDetId,
    });
  };

  okUpdate = () => {
    const { form, dispatch } = this.props;
    const { tskDetId, current, pageSize } = this.state;
    form.validateFields(['listAss'], (err, values) => {
      if (!err) {
        dispatch({
          type: 'annualbasic/fetchUpdateTsk',
          payload: { ...values, tskDetId },
        }).then(res => {
          if (res.success) {
            this.getList(2,current,pageSize);
            this.setState({
              visUpdate: false,
            });
          } else {
            message.warning(res.message || '服务端错误');
          }
        });
      }
    });
  };

  cancelUpdate = () => {
    this.setState({
      visUpdate: false,
    });
  };

  render() {
    const { annualbasic, form, loadingEmp, loadingCust } = this.props;
    const {
      selectedRows,
      selectedRowKeys,
      visAccoNum,
      userType,
      visUpdate,
      updateInfor,
      tempActiveKey,
    } = this.state;
    const { getFieldDecorator } = form;
    const downloadButton = Number(tempActiveKey) === 3 && (
      <Button style={{ marginBottom: 12 }} type="primary" onClick={this.downCsAddEmp}>
        下载更新增员
      </Button>
    );
    const diffShow =
      Number(userType) === 4 && Number(tempActiveKey) === 1 ? styles.show : styles.hide;
    const cusColumns = [
      {
        title: '客户名称',
        dataIndex: 'custName',
      },
      {
        title: '签约方',
        dataIndex: 'ordSndrName',
      },
      // 只有运行待采集有采集状态
      {
        title: '采集状态',
        dataIndex: 'collectName',
        className: diffShow,
      },
      {
        title: '涉及人数',
        dataIndex: 'planColtNum',
      },
      {
        title: '所属负责人',
        dataIndex: 'blngCs',
      },
      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', width: 200 } }),
        render: record => (
          <span>
            {(Number(tempActiveKey) === 1 || Number(tempActiveKey) === 3) &&
              Number(userType) === 1 && (
                <span>
                  <a
                    onClick={() =>
                      router.push(
                        `/more/annualbasic/progress?yearAdjTskId=${
                          annualbasic.yearAdjTskId
                        }&&custId=${record.custId}&&areaId=${annualbasic.areaId}`
                      )
                    }
                  >
                    {String(record.state) === '3' ? '重新上传' : '上传'}
                  </a>

                  <Divider type="vertical" />
                </span>
              )}

            <a onClick={() => this.downloadExcel(record)}>下载</a>
          </span>
        ),
      },
      // 客服有上传
    ];
    const accuColumns = [
      {
        title: '账户名称',
        dataIndex: 'accoName',
      },
    ];
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };

    return (
      <div>
        <PageHeaderWrapper>
          <Card
            title={
              <span style={{ fontWeight: 'bolder' }}>年度基数调整——{annualbasic.areaName} </span>
            }
            bordered={false}
          >
            <DescriptionList style={{ marginBottom: 10 }}>
              <Description term="调整年度">{annualbasic.adjYear || '--'}</Description>
              <Description term="地区">{annualbasic.areaName || '--'}</Description>
              <Description term="客户数量">{annualbasic.custNum || '--'}</Description>
            </DescriptionList>
            <DescriptionList style={{ marginBottom: 10 }}>
              <Description term="员工数量">{annualbasic.empNum || '--'}</Description>
              <Description term="采集人员范围">
                {annualbasic.adjYm ? moment(annualbasic.adjYm).format('YYYY-MM') : '--'}
              </Description>
              <Description term="采集任务开始日期">
                {annualbasic.adjTskBeginDate
                  ? moment(annualbasic.adjTskBeginDate).format('YYYY-MM-DD')
                  : '--'}
              </Description>
            </DescriptionList>
            <DescriptionList style={{ marginBottom: 10 }}>
              <Description term="采集任务结束日期">
                {moment(annualbasic.adjTskEndDate).format('YYYY-MM-DD') || '--'}
              </Description>
              <Description term="生效年月">
                {annualbasic.validYm ? moment(annualbasic.validYm).format('YYYY-MM') : '--'}
              </Description>

              <Description term="附件">
                {annualbasic.affix && annualbasic.affix.length
                  ? this.addLink(annualbasic.affix)
                  : '--'}
              </Description>
            </DescriptionList>
            <DescriptionList style={{ marginBottom: 10 }}>
              {/* 加鼠标滑过功能 */}
              <Description term="政策解读">
                {annualbasic.remark ? (
                  <Tooltip placement="topLeft" title={annualbasic.remark}>
                    <p
                      style={{
                        WebkitBoxOrient: 'vertical',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',
                        overflow: 'hidden',
                        wordBreak: 'break-all',
                        width: '250px',
                      }}
                    >
                      {annualbasic.remark}
                    </p>
                  </Tooltip>
                ) : (
                  '--'
                )}
              </Description>
              <Description term="创建日期">
                {moment(annualbasic.creTime).format('YYYY-MM-DD HH:DD') || '--'}
              </Description>
            </DescriptionList>

            <Tabs
              activeKeyDetail={annualbasic.activeKeyDetail}
              onChange={this.tabPaneChange}
              tabBarExtraContent={downloadButton}
            >
              <TabPane tab="客户列表" key="1">
                <div
                  className={styles.tableListForm}
                  style={{
                    margintop: 4,
                    marginBottom: 16,
                    paddingTop: 24,
                    paddingRight: 24,
                    backgroundColor: '#fafafa',
                  }}
                >
                  <Form layout="inline">
                    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                      <Col md={8} sm={24} offset={1}>
                        <FormItem label="客户名称" {...this.tableSearchLayout}>
                          {getFieldDecorator('custId')(
                            Number(userType === 1) ? (
                              <Customer allowClear />
                            ) : (
                              <Customer attr allowClear />
                            )
                          )}
                        </FormItem>
                      </Col>
                      {/* 只有运行有采集状态 */}
                      {Number(userType) === 4 && Number(tempActiveKey) === 1 && (
                        <Col md={9} sm={24}>
                          <FormItem label="采集状态" {...this.tableSearchLayout}>
                            {getFieldDecorator('state')(
                              <Select placeholder="请选择">
                                <Option value="1"> 待采集 </Option>
                                <Option value="3">已采集</Option>
                              </Select>
                            )}
                          </FormItem>
                        </Col>
                      )}

                      <Col md={6} sm={24}>
                        <span>
                          <Button
                            type="primary"
                            onClick={() => this.getList(annualbasic.activeKeyDetail)}
                            style={{ marginRight: 10 }}
                          >
                            查询
                          </Button>
                          <Button onClick={this.handleFormReset}>重置</Button>
                        </span>
                      </Col>
                    </Row>
                  </Form>
                </div>
                <div>
                  {/* 只有运行已采集有 */}

                  <StandardTable
                    selectedRows={selectedRows}
                    selectedRowKeys={selectedRowKeys}
                    loading={loadingCust}
                    data={annualbasic.pageDataDetail}
                    rowKey={() => Math.random(0, 1)}
                    columns={cusColumns}
                    rowSelection={null}
                    onSelectRow={this.handleSelectRows}
                    onChange={this.handleStandardTableChange}
                  />
                </div>
              </TabPane>
              <TabPane tab="员工列表" key="2">
                <div
                  className={styles.tableListForm}
                  style={{
                    margintop: 4,
                    marginBottom: 16,
                    paddingTop: 24,
                    paddingRight: 24,
                    backgroundColor: '#fafafa',
                  }}
                >
                  <Form layout="inline">
                    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                      <Col md={7} sm={24} offset={1}>
                        <FormItem label="客户名称" {...this.tableSearchLayout}>
                          {getFieldDecorator('custId')(
                            Number(userType === 1) ? (
                              <Customer allowClear />
                            ) : (
                              <Customer attr allowClear />
                            )
                          )}
                        </FormItem>
                      </Col>
                      <Col md={5} sm={24}>
                        <FormItem label="姓名" {...this.tableSearchLayout}>
                          {getFieldDecorator('empName')(<Input placeholder="请输入" />)}
                        </FormItem>
                      </Col>
                      <Col md={6} sm={24}>
                        <FormItem label="证件号" {...this.tableSearchLayout}>
                          {getFieldDecorator('certNo')(<Input placeholder="请输入" />)}
                        </FormItem>
                      </Col>
                      <Col md={5} sm={24}>
                        <span>
                          <Button
                            type="primary"
                            onClick={() => this.getList(annualbasic.activeKeyDetail)}
                            style={{ marginRight: 10 }}
                          >
                            查询
                          </Button>
                          <Button onClick={this.handleFormReset}>重置</Button>
                        </span>
                      </Col>
                    </Row>
                  </Form>
                </div>
                <StandardTable
                  selectedRows={selectedRows}
                  selectedRowKeys={selectedRowKeys}
                  loading={loadingEmp}
                  data={annualbasic.pageDataDetail}
                  rowSelection={null}
                  rowKey={() => Math.random(0, 1)}
                  columns={annualbasic.dynamicColumn}
                  onSelectRow={this.handleSelectRows}
                  onChange={this.handleStandardTableChange}
                />
              </TabPane>
            </Tabs>
          </Card>
          <Modal
            title="账户"
            visible={visAccoNum}
            onOk={this.okAccoNum}
            onCancel={this.cancelAccoNum}
          >
            <Table
              columns={accuColumns}
              dataSource={annualbasic.accoNameList}
              rowKey={record => record.accoId}
              pagination={false}
            />
          </Modal>
          {updateInfor && (
            <Modal
              title="修改"
              visible={visUpdate}
              onOk={this.okUpdate}
              onCancel={this.cancelUpdate}
              destroyOnClose
            >
              <Form {...formItemLayout}>
                <FormItem label="姓名" className={style.formFar}>
                  <span>{updateInfor.empName}</span>
                </FormItem>
                <FormItem label="证件号" className={style.formFar}>
                  <span>{updateInfor.certNo}</span>
                </FormItem>
                <FormItem label="客户" className={style.formFar}>
                  <span>{updateInfor.custName}</span>
                </FormItem>
                {updateInfor.listAss.map((item, index) => (
                  <div key={item.ass}>
                    <FormItem label={item.assName} style={{ display: 'none' }}>
                      {getFieldDecorator(`listAss[${index}][ass]`, { initialValue: item.ass })(
                        <span>{item.ass}</span>
                      )}
                    </FormItem>
                    <span
                      style={{
                        display: 'inline-block',
                        textAlign: 'right',
                        marginTop: 4,
                        color: '#262626',
                        opacity: 0.85,
                        width: 119,
                      }}
                    >
                      {item.assName}：
                    </span>

                    <FormItem style={{ display: 'inline-block' ,width:250}}>
                      <span>
                        {getFieldDecorator(`listAss[${index}][aftPayWage]`, {
                          initialValue: item.aftPayWage,
                          rules: [
                            {
                              required: true,
                              message: '请填写大于1小于9999999.99',
                              pattern: /^[1-9]{1}[0-9]{0,6}(\.[0-9]{1,2})?$/,
                            },
                          ],
                        })(<Input style={{ width: 150, marginLeft: 8 }} />)}
                      </span>
                    </FormItem>
                  </div>
                ))}
                <FormItem label="&nbsp;" colon={false} style={{ marginTop: -17, marginLeft: 0 }}>
                  <span style={{ color: '#f00' }}>注：请先确认好，再调整数据</span>
                </FormItem>
              </Form>
            </Modal>
            //   <Modal
            //   title="修改"
            //   visible={visUpdate}
            //   onOk={this.okUpdate}
            //   onCancel={this.cancelUpdate}
            //   destroyOnClose
            // >
            //   <Form {...formItemLayout}>
            //     <FormItem label="姓名" className={style.formFar}>
            //       <span>{updateInfor.empName}</span>
            //     </FormItem>
            //     <FormItem label="证件号" className={style.formFar}>
            //       <span>{updateInfor.certNo}</span>
            //     </FormItem>
            //     <FormItem label="客户" className={style.formFar}>
            //       <span>{updateInfor.custName}</span>
            //     </FormItem>
            //     {updateInfor.listAss.map((item, index) => (
            //       <div key={item.ass}>
            //         <FormItem label={item.assName} style={{ display: 'none' }}>
            //           {getFieldDecorator(`listAss[${index}][ass]`, { initialValue: item.ass })(
            //             <span>{item.ass}</span>
            //           )}
            //         </FormItem>
            //         <span
            //           style={{
            //             display: 'inline-block',
            //             textAlign: 'right',
            //             marginTop: 8,
            //             color: '#262626',
            //             opacity: 0.85,
            //             width: 119,
            //           }}
            //         >
            //           {item.assName}：
            //         </span>
            //         <span
            //           style={{
            //             display: 'inline-block',
            //             textAlign: 'center',
            //             marginTop: 8,
            //             marginRight: 2,
            //             width: 78,
            //           }}
            //         >
            //           {item.aftPayWage || '--'}
            //         </span>
            //         调整
            //         <FormItem style={{ display: 'inline-block' }}>
            //           <span>
            //             {getFieldDecorator(`listAss[${index}][aftPayWage]`, {
            //               rules: [
            //                 {
            //                   required: true,
            //                   message: '请填写大于1小于9999999.99',
            //                   pattern: /^[1-9]{1}[0-9]{0,6}(\.[0-9]{1,2})?$/,
            //                 },
            //               ],
            //             })(<Input style={{ width: '100%', marginLeft: 8 }} />)}
            //           </span>
            //         </FormItem>
            //       </div>
            //     ))}
            //     <FormItem label="&nbsp;" colon={false} style={{ marginTop: -17, marginLeft: -40 }}>
            //       <span style={{ color: '#f00' }}>注：请先确认好，再调整数据</span>
            //     </FormItem>
            //   </Form>
            // </Modal>
          )}
        </PageHeaderWrapper>
        <FooterToolbar>
          <Button style={{ marginLeft: 15 }} onClick={this.close}>
            返回
          </Button>
        </FooterToolbar>
      </div>
    );
  }
}

export default DetailInfor;
